package jsj.open.lib

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Environment
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import jsj.open.lib.ext.isAudio
import jsj.open.lib.ext.isPicture
import jsj.open.lib.ext.isVideo
import jsj.open.lib.fileview.FileBean
import jsj.open.lib.fileview.FileExploer
import jsj.open.lib.fileview.ResType

class FileViewer(context: Context, attrs: AttributeSet?, defStyleAttr: Int) :FrameLayout(context, attrs, defStyleAttr) {


    private var mCallback:Callback?=null
    public interface Callback{
        fun onPath(path:String,fileName:String)
        fun onClose()
    }
    fun setCallback(c:Callback){
        mCallback = c
    }
    public var rootPath:String = Environment.getExternalStorageDirectory().absolutePath
    private var filters = mutableListOf<String>()

    constructor(context: Context):this(context,null,0)
    constructor(context: Context,attrs: AttributeSet?):this(context,attrs,0)

    private val rv:RecyclerView by lazy { findViewById(R.id.rv_list) }
    private val explode:FileExploer by lazy { FileExploer() }
    private var fileList = mutableListOf<FileBean>().apply {
        addAll(explode.explode().filter { baseFilter(it) })
    }
    fun refresh(){
        refresh(rootPath)
    }
    fun refresh(path:String= rootPath){
        fileList.clear()
        fileList.addAll(explode.explode(path).filter { baseFilter(it) })
        adapter.notifyDataSetChanged()
    }
    var adapter = object :BaseQuickAdapter<FileBean,BaseViewHolder>(R.layout.item_file,fileList){
        override fun convert(holder: BaseViewHolder, item: FileBean) {
            holder.setText(R.id.tv_name,item.name)
            val imageView = holder.getView<ImageView>(R.id.iv_fold)
            when(getResType(item)){
                ResType.dir -> {
                    imageView.setImageResource(R.drawable.svg_folder_filled)
                    imageView.imageTintList = ColorStateList.valueOf(Color.parseColor("#F9A825"))
                }
                ResType.video -> {
                    imageView.setImageResource(R.drawable.svg_video)
                    imageView.imageTintList = ColorStateList.valueOf(Color.parseColor("#FF2196F3"))
                }
                ResType.audio -> {
                    imageView.setImageResource(R.drawable.svg_music)
                    imageView.imageTintList = ColorStateList.valueOf(Color.parseColor("#FFE91E63"))
                }
                ResType.picture -> {
                    imageView.setImageResource(R.drawable.svg_picture)
                    imageView.imageTintList = ColorStateList.valueOf(Color.parseColor("#009688"))
                }
                else->{
                    imageView.setImageResource(R.drawable.svg_document_filled)
                    imageView.imageTintList = ColorStateList.valueOf(Color.parseColor("#FF96A3A2"))
                }
            }
        }
    }

    private fun getResType(item: FileBean): ResType {
        if(item.isDir) return ResType.dir
        else if(item.name.isVideo) return ResType.video
        else if(item.name.isAudio) return ResType.audio
        else if(item.name.isPicture) return ResType.picture
        else return ResType.doc
    }

    init {
        explode.onPathChange = {
                path,fold->
            findViewById<TextView>(R.id.tv_span1).text = path
            findViewById<TextView>(R.id.tv_span2).text = fold
        }
        LayoutInflater.from(context).inflate(R.layout.layout_file_viewer,this,true)
        rv.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL,false)
        rv.adapter = adapter
        adapter.setOnItemClickListener { apt, v, position ->
            adapter.data[position].apply {
                if(isDir){
                    fileList.clear()
                    fileList.addAll(explode.jump(path).filter { baseFilter(it) })
                    adapter.notifyDataSetChanged()
                }else{
                    var data = adapter.data[position]
                    mCallback?.onPath(data.path,data.name)
                }
            }
        }
        findViewById<ImageView>(R.id.iv_return).setOnClickListener {
            explode.back()?.let {
                fileList.clear()
                fileList.addAll(it.filter { baseFilter(it) })
                adapter.notifyDataSetChanged()
            }
        }
        findViewById<ImageView>(R.id.iv_close).setOnClickListener {
            mCallback?.onClose()
        }
        setOnTouchListener { _, _ -> true }
    }

    private fun baseFilter(fileBean: FileBean):Boolean{
        return !fileBean.name.startsWith(".") && customFilter(fileBean)
    }

    private fun customFilter(fileBean: FileBean): Boolean {
        if(filters.size==0 || fileBean.isDir) return true
        return filters.any { fileBean.name.contains(it) }
    }

    fun setFilter(vararg list:String){
        filters.clear()
        filters.addAll(list)
    }
    fun show(){
        visibility = View.VISIBLE
    }
    fun hide(){
        visibility = View.INVISIBLE
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        findViewById<TextView>(R.id.tv_span1).maxWidth = w/2
    }

}